package com.vieewer.btdemo.view.mycamera;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.hardware.Camera;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.lindroid.androidutilskt.extension.SpUtil;
import com.lindroid.androidutilskt.statics.AppManager;
import com.vieewer.btdemo.R;
import com.vieewer.btdemo.base.BaseActivity;
import com.vieewer.btdemo.utils.ImageUtils;
import com.vieewer.btdemo.widget.mycamera.CameraSurfaceView;
import com.vieewer.btdemo.widget.mycamera.MediaActionSwitchView;
import com.vieewer.btdemo.widget.mycamera.RecordButton;
import com.vieewer.btdemo.wifimain.MainActivity;
import org.jetbrains.annotations.NotNull;
import java.io.File;
import static com.vieewer.btdemo.common.Constants.SP_KEY_CAMERA_SCENE_MODE;

public class SurfaceCameraActivity extends BaseActivity implements View.OnClickListener {

    private static final String TAG = "SurfaceCameraActivity";
    public static final int SCENE_MODE_NORMAL = 0;
    public static final int SCENE_MODE = 1;

    private ImageView mCloseIv;
    private ImageView mSwitchCameraIv;
    private ImageView mTakePictureIv;
    private ImageView mPictureIv;
    private TextView mTakeVideo;
    private CameraSurfaceView mCameraView;
    private RecordButton mRecordButton;
    private MediaActionSwitchView mediaActionSwitchView;

    private CameraProxy mCameraProxy;
    private boolean bTakePhotoMode = true;
    private boolean mHasFocus;
    public boolean mHDRSceneMode = false;
    private long mTime = 0;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_surface_camera);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        initView();
        init();

    }


    public static void startActivity(@NotNull Context activity, int tag) {
        Intent intent = new Intent(activity, SurfaceCameraActivity.class);
        intent.putExtra("Tag", tag);
        activity.startActivity(intent);
    }

    private void init() {
        createFile(); //创建照片存储文件夹
        int mode = getIntent().getIntExtra("Tag", SCENE_MODE_NORMAL);
        if (mode == SCENE_MODE_NORMAL) {
            mHDRSceneMode = false;
        } else if (mode == SCENE_MODE ) {
            //设置为HDR模式拍照变HDR，其它都是非HDR，包括翻译等
            mHDRSceneMode = SpUtil.getSpBoolean(SP_KEY_CAMERA_SCENE_MODE, false);
        }
        Log.i("yjj", "hdr 111");


    }


    private void createFile() {
        File file = new File(ImageUtils.GALLERY_PATH);
        if(!file.exists()){//如果文件夹不存在
            file.mkdir();//创建文件夹
        }
    }

    private void initView() {
        mCloseIv = findViewById(R.id.toolbar_close_iv);
        mCloseIv.setOnClickListener(this);
        mSwitchCameraIv = findViewById(R.id.toolbar_switch_iv);
        mSwitchCameraIv.setOnClickListener(this);
        mTakePictureIv = findViewById(R.id.take_picture_iv);
        mTakePictureIv.setOnClickListener(this);
        mPictureIv = findViewById(R.id.picture_iv);
        mPictureIv.setOnClickListener(this);
        mPictureIv.setImageBitmap(ImageUtils.getLatestThumbBitmap());
        mCameraView = findViewById(R.id.camera_view);
        mTakeVideo = findViewById(R.id.take_video_tv);
        mTakeVideo.setOnClickListener(this);
        mRecordButton = findViewById(R.id.record_button);
        mRecordButton.setOnClickListener(this);
        mediaActionSwitchView = findViewById(R.id.photo_video_camera_switcher);
        mediaActionSwitchView.setOnClickListener(this);
        mCameraProxy = mCameraView.getCameraProxy();
        mCameraProxy.setOnCallBackListener(() -> mRecordButton.displayVideoRecordStateReady());
        mediaActionSwitchView.displayActionWillSwitchPhoto();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.toolbar_close_iv:
                finish();
                break;
            case R.id.toolbar_switch_iv:
                mCameraProxy.switchCamera();
                mCameraProxy.startPreview(mCameraView.getHolder());
                break;
            case R.id.take_picture_iv:
                mCameraProxy.takePicture(mPictureCallback);
                break;
            case R.id.picture_iv:
                Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivity(intent);
                break;
            case R.id.take_video_tv:
                mCameraProxy.takeVideo();
                break;
            case R.id.record_button:
                takePhotoOrVideo();
                break;

            case R.id.photo_video_camera_switcher:
                switchMode();
                break;
        }
    }

    private void switchMode() {
        if (bTakePhotoMode) {
            mRecordButton.displayVideoRecordStateReady();
            mediaActionSwitchView.displayActionWillSwitchVideo();
        } else {
            mRecordButton.displayPhotoState();
            mediaActionSwitchView.displayActionWillSwitchPhoto();
        }
        bTakePhotoMode = !bTakePhotoMode;
    }

    private void takePhotoOrVideo() {
        if (bTakePhotoMode) {
            mTime = System.currentTimeMillis();
            Log.i("yjj",  "onPictureTaken 111 >>>> " + mTime);
            mCameraProxy.takePicture(mPictureCallback);
        } else {
            mRecordButton.displayVideoRecordStateInProgress();
            mCameraProxy.takeVideo();
        }
    }


    private final Camera.PictureCallback mPictureCallback = new Camera.PictureCallback() {
        @Override
        public void onPictureTaken(byte[] data, Camera camera) {

            Log.i("yjj",  "onPictureTaken 222 >>>> " + (System.currentTimeMillis() - mTime)/1000);

            mCameraProxy.startPreview(mCameraView.getHolder()); // 拍照结束后继续预览
            new ImageSaveTask().execute(data); // 保存图片
            Toast.makeText(SurfaceCameraActivity.this, "拍照成功", Toast.LENGTH_SHORT).show();

        }
    };


    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        mHasFocus = hasFocus;
        super.onWindowFocusChanged(hasFocus);
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        Log.i("yjj",  "currentActivity >>>" +  AppManager.currentActivity().getLocalClassName());

        if ( mHasFocus && AppManager.currentActivity().getLocalClassName().equals("view.mycamera.SurfaceCameraActivity")) {
            if (keyCode == 22) {       //触控板往前滑动
                mCameraProxy.handleZoom(true);
            } else if (keyCode == 21) { //触控板往后滑动
                mCameraProxy.handleZoom(false);
            }

            //按功能键切换拍照和录像模式
            if (keyCode == 119) {  //Fn按键对应键值为119
                switchMode();
            }

        }

        return super.onKeyUp(keyCode, event);
    }





    private class ImageSaveTask extends AsyncTask<byte[], Void, Bitmap> {

        @Override
        protected Bitmap doInBackground(byte[]... bytes) {

            long time = System.currentTimeMillis();
            Bitmap bitmap = BitmapFactory.decodeByteArray(bytes[0], 0, bytes[0].length);
            Log.d(TAG, "BitmapFactory.decodeByteArray time: " + (System.currentTimeMillis() - time));
            int rotation = mCameraProxy.getLatestRotation();
            time = System.currentTimeMillis();
            //Bitmap rotateBitmap = ImageUtils.rotateBitmap(bitmap, rotation, mCameraProxy.isFrontCamera(), true);
            Log.d(TAG, "rotateBitmap time: " + (System.currentTimeMillis() - time));
            time = System.currentTimeMillis();
            ImageUtils.saveBitmap(bitmap);
            Log.d(TAG, "saveBitmap time: " + (System.currentTimeMillis() - time));
            bitmap.recycle();
            return ImageUtils.getLatestThumbBitmap();
        }

        @Override
        protected void onPostExecute(Bitmap bitmap) {
            //mPictureIv.setImageBitmap(bitmap);
        }
    }




}
